package cn.lliiooll.launcher.update;

import cn.lliiooll.launcher.window.Window;

import javax.swing.*;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class FileSet {
	
	public static String info = "[信息] ";
	public static String error = "[错误] ";
	public static String npath;
	
	public static void print(String message) {
		System.out.println(message);
	}

	public static void createFile(String filename, String path) {
		File f = new File(path);//设置新的量
		
		if(f.exists()) {//判断文件夹是否存在
			//存在，不做任何动作
		}else {//否则
			f.mkdir();//创建文件夹
		}
		
		File file = new File(path,filename);//设置新的量
	
		if(file.exists()) {//判断文件是否存在
			
		}else {
			try {//这里进行IO操作
				file.createNewFile();//成功，则创建文件
			} catch (IOException e) {
				//失败，则打印出错误
				e.printStackTrace();
			}
		}
		print(info + "文件创建完成");
	}
	
	@SuppressWarnings("resource")
	public static void writeFile(String text, String filename, String path) {
		File file = new File(path,filename);
		if(!(file.exists())) {
			print(error + "文件不存在");
			print(info + "创建文件");
			createFile(filename, path);
			try {
				//成功，则设置下面的量
				PrintStream ps = new PrintStream(new FileOutputStream(file));
				ps.println(text);//在这里写入文件
				print("写入完成");
				} catch (FileNotFoundException e) {
				// TODO 自动生成的 catch 块
				//失败，抛错
				e.printStackTrace();
			}
		}else {
			print(info + "检测到文件");
			try {
				//成功，则设置下面的量
				PrintStream ps = new PrintStream(new FileOutputStream(file));
				ps.println(text);//在这里写入文件
				print(info + "写入完成");
				} catch (FileNotFoundException e) {
				// TODO 自动生成的 catch 块
				//失败，抛错
				e.printStackTrace();
			}
		}
	}
	
	public static void readFile(String filename, String filepath) {
		File f = new File(filepath + "\\" + filename);   
		if(f.exists()) {
	        byte b[] = new byte[1024];   
	        int len = 0;   
	        int temp= 0;          //所有读取的内容都使用temp接收   
	        try {
	        	InputStream in = new FileInputStream(f);
				while((temp=in.read())!=-1){    //当没有读取完时，继续读取   
				    b[len]=(byte)temp;   
				    len++;   
				}
				in.close(); 
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}   
	        System.out.println("文件内容为\n");
	        System.out.println(new String(b,0,len));
		}else {
			System.out.println("没有找到文件");
		} 

	}
	
	public static void copyFile(String oldpath,String newpath, String newname){
		File fold = new File(oldpath);   
		File fnew = new File(newpath);
		File fnewname = new File(newpath + "\\",newname);
		if(!(fold.exists())) {
			System.out.println("源文件不存在");
		}else {
			fnew.mkdir();
			try {
				fnewname.createNewFile();
			} catch (IOException e1) {
				// TODO 自动生成的 catch 块
				e1.printStackTrace();
			}
				byte[] b = new byte[1024];
				int n = 0;
				try {
					FileInputStream in = new FileInputStream(fold);
					FileOutputStream out = new FileOutputStream(newpath + "\\" + newname);
					while((n = in.read(b)) != -1) {
						out.write(b, 0, n);
					}
					out.close();
					in.close();
				} catch (Exception e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
		}
	}
	
	public static void shearFile(String oldpath,String newpath, String newname){
		File fold = new File(oldpath);   
		File fnew = new File(newpath);
		File fnewname = new File(newpath + "\\",newname);
		if(!(fold.exists())) {
			System.out.println("源文件不存在");
		}else {
			fnew.mkdir();
			try {
				fnewname.createNewFile();
			} catch (IOException e1) {
				// TODO 自动生成的 catch 块
				e1.printStackTrace();
			}
				byte[] b = new byte[1024];
				int n = 0;
				try {
					FileInputStream in = new FileInputStream(fold);
					FileOutputStream out = new FileOutputStream(newpath + "\\" + newname);
					while((n = in.read(b)) != -1) {
						out.write(b, 0, n);
					}
					out.close();
					in.close();
					fold.delete();
					System.out.println("剪切完成");
				} catch (Exception e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
		}
	}
	
	public static void copyDir(String oldpath,String newpath) {

		File f = new File(oldpath);
		File[] fs = f.listFiles();
		for(int i = 0; i < fs.length; i++) {
			if(fs[i].isDirectory()) {
				File newd = new File(newpath + "\\" + fs[i].getName());
				newd.mkdir();
				copyDir(oldpath + "\\" + fs[i].getName(),newpath + "\\" + fs[i].getName());
			}else {
				copyFile(fs[i].getAbsolutePath(), newpath + "\\", fs[i].getName());
			}
		}
		
	}
	
	public static void delDirFiles(String path) {
		File f = new File(path);
		File[] fs = f.listFiles();
		for(int i = 0; i < fs.length; i++) {
			if(fs[i].isDirectory()) {
				delDirFiles(path + "\\" + fs[i].getName());
			}else {
				fs[i].delete();
			}
		}
	}
	
	public static void update(String oldpath,String newpath) {
		Window.ujpb.setString("开始删除旧文件");
		Window.ujpb.setIndeterminate(true);
		File f = new File(oldpath);
		if(f.exists()) {
			delDirFiles(oldpath);
			delDir(oldpath);
		}
		Window.ujpb.setString("开始复制文件");
		copyDir(newpath, oldpath);
		Window.ujpb.setString("开始清除缓存文件");
		delDirFiles("tmp");
		delDirFiles("download");
		delDir("tmp");
		delDir("download");
		try {
			Socket c1 = new Socket(Update.link,Update.port);
			DataInputStream dis = new DataInputStream(c1.getInputStream());
			OutputStream outs1 = c1.getOutputStream();
			DataOutputStream out1 = new DataOutputStream(outs1);
			out1.writeInt(0);
			String ver = new String(dis.readUTF());
			File versionfile = new File("version.txt");
			if(!(versionfile.exists())) {
				//Repair.versionFileRepair();
				JOptionPane.showMessageDialog(null,"没有找到版本文件,所以无法正常更新", "错误",JOptionPane.ERROR_MESSAGE); 
				System.exit(0);
			}else {
				FileOutputStream fos1 = new FileOutputStream(versionfile);
				try {
					//OutputStream ots = c.getOutputStream();
					//DataOutputStream out = new DataOutputStream(ots);
					//out.writeUTF("1");
					fos1.write(ver.getBytes());
					c1.close();
					fos1.close();
					dis.close();
				} catch (Exception e) {
					JOptionPane.showMessageDialog(null,"发生了一个错误导致无法继续更新", "错误",JOptionPane.ERROR_MESSAGE); 
					e.printStackTrace();
				}
			}
		} catch (UnknownHostException e) {
			JOptionPane.showMessageDialog(null,"无法连接到服务器", "错误",JOptionPane.ERROR_MESSAGE); 
			System.exit(0);
			e.printStackTrace();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null,"发生了一个错误导致无法继续更新", "错误",JOptionPane.ERROR_MESSAGE); 
			System.exit(0);
			e.printStackTrace();
		}
		Window.uw.dispose();
		Window.updateCompeleteWindow();
	}

	private static void delDir(String path) {
		File f = new File(path);
		File[] fs = f.listFiles();
		for(int i = 0; i < fs.length; i++) {
			if(fs[i].isDirectory()) {
				fs[i].delete();
			}else {
				delDir(path + "\\" + fs[i].getName());
			}
		}
		
	}
	
	
}
